#include "Toast.h"
#include <QApplication>
#include <QTextBrowser>

namespace TWCore
{
	int Toast::i_toastMaxWidth = 210;
	int Toast::i_marginX = 0;
	int Toast::i_marginY = 0;
	Toast::Toast(QWidget* parent,int i):
				QLabel(parent),
				i_index(i)
	{
		setObjectName("toastLabel");
		setAlignment(Qt::AlignCenter);
		setWordWrap(true);
		m_timer.setSingleShot(true);
		connect(&m_timer,SIGNAL(timeout()),this,SLOT(timeout()));
		ensurePolished();
	}

	Toast::~Toast(){}

	void Toast::show(const QString& msg,int x,int y,int duration)
	{
		QFontMetrics metric(font());
		int w = metric.width(msg);

		if(w>i_toastMaxWidth)
			w = i_toastMaxWidth;

		QTextBrowser textEdit;
		textEdit.setPlainText(msg);
		textEdit.setLineWrapColumnOrWidth(i_toastMaxWidth);
		textEdit.setAttribute(Qt::WA_DontShowOnScreen);
		textEdit.show();
		int h = textEdit.document()->size().height();

		setText(msg);
		setGeometry(x-w/2,y-h,w+i_marginX,h+i_marginY);

		m_timer.start(duration);
		QLabel::show();
	}

	void Toast::timeout()
	{
		hide();
		emit fadeOut(i_index);
	}

}
